import {
  Button,
  Checkbox,
  DatePicker,
  Drawer,
  Form,
  Input,
  message,
  Select,
  Table,
  Tag,
  TreeSelect,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import {
  apiChannelAll,
  apiChannelTagsAll,
  apiNovelChannelAuth,
  apiSaveNovelChannelAuth,
} from "~/api";
import { DictType } from "~/common/enum/dict.enum";
import { useDictMap, useDictsMap } from "~/contexts/dict";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { IChannelTag } from "~/types/manage/channel/list";
import type { INovel, INovelChannelAuth } from "~/types/manage/content/novel";
import { dictToOption, transTreeToAntdTreeData } from "~/utils/ui.util";

interface Props {
  visible: boolean;
  novel: INovel | null;
  onClose?: () => void;
  onOk?: () => void;
}

export default function NovelChannelAuthDrawer(props: Props) {
  const tableHeight = useTableHeight(325);
  const [form] = Form.useForm<{
    rows: INovelChannelAuth[];
  }>();
  const [channelTagTreeMap, setChannelTagTreeMap] =
    useState<Record<number, IChannelTag[]>>();

  const dictsMap = useDictsMap([
    DictType.NOVEL_CHANNEL_AUTH_TYPE,
    DictType.NOVEL_CHANNEL_AUTH_STATUS,
  ]);
  const dictMap = useDictMap();

  const _ui: {
    tableColumns: ColumnsType<INovelChannelAuth>;
  } = {
    tableColumns: [
      {
        title: (
          <div className="flex flex-col gap-2">
            <span>渠道名称</span>
            <span>内容类型</span>
          </div>
        ),
        dataIndex: ["channelInfo", "name"],
        key: "channelInfo.name",
        fixed: "left",
        width: 100,
        render: (_, __, index) => {
          const record: INovelChannelAuth = form.getFieldValue(["rows", index]);
          console.log("record", record);
          return (
            <div className="flex flex-col gap-2">
              <span>{record?.channelInfo?.name || "--"}</span>
              <div className="flex flex-wrap">
                {record.channelInfo?.channelNovelConfig?.kind?.map((item) => {
                  return <Tag key={item}>{dictMap[item].label}</Tag>;
                })}
                {record.channelInfo?.channelNovelConfig?.lengthType?.map(
                  (item) => {
                    return <Tag key={item}>{dictMap[item].label}</Tag>;
                  },
                )}
                {record.channelInfo?.channelNovelConfig?.contentType?.map(
                  (item) => {
                    return <Tag key={item}>{dictMap[item].label}</Tag>;
                  },
                )}
              </div>
            </div>
          );
        },
      },
      {
        title: "渠道标签",
        dataIndex: "channelTagId",
        key: "channelTagId",
        width: 200,
        render: (_, __, index) => {
          const record: INovelChannelAuth = form.getFieldValue(["rows", index]);
          return (
            <Form.Item name={[index, "channelTagId"]}>
              <TreeSelect
                placeholder="请选择渠道标签"
                allowClear
                treeLine={true}
                treeData={transTreeToAntdTreeData(
                  channelTagTreeMap?.[record.channelId] || [],
                  "",
                )}
                treeNodeLabelProp={"label"}
              />
            </Form.Item>
          );
        },
      },
      {
        title: "渠道标题",
        dataIndex: "channelTitle",
        key: "channelTitle",
        width: 180,
        render: (_, __, index) => {
          return (
            <Form.Item name={[index, "channelTitle"]}>
              <Input.TextArea autoSize={{ minRows: 3, maxRows: 3 }} />
            </Form.Item>
          );
        },
      },
      {
        title: "授权类型",
        dataIndex: "authType",
        key: "authType",
        width: 120,
        render: (_, __, index) => {
          return (
            <Form.Item name={[index, "authType"]}>
              <Select
                options={dictToOption(dictsMap.NOVEL_CHANNEL_AUTH_TYPE)}
              />
            </Form.Item>
          );
        },
      },
      {
        title: "授权状态",
        dataIndex: "authStatus",
        key: "authStatus",
        width: 120,
        render: (_, __, index) => {
          return (
            <Form.Item name={[index, "authStatus"]}>
              <Select
                options={dictToOption(dictsMap.NOVEL_CHANNEL_AUTH_STATUS)}
              />
            </Form.Item>
          );
        },
      },
      {
        title: "授权开始时间",
        dataIndex: "authStartDateDayjs",
        key: "authStartDateDayjs",
        width: 140,
        render: (_, __, index) => {
          return (
            <Form.Item name={[index, "authStartDateDayjs"]}>
              <DatePicker />
            </Form.Item>
          );
        },
      },
      {
        title: "授权截止时间",
        dataIndex: "authExpireDateDayjs",
        key: "authExpireDate",
        width: 140,
        render: (_, __, index) => {
          return (
            <Form.Item name={[index, "authExpireDateDayjs"]}>
              <DatePicker />
            </Form.Item>
          );
        },
      },
      {
        title: "是否有导语章节",
        dataIndex: "hasDefaultIntro",
        key: "hasDefaultIntro",
        width: 120,
        render: (_, __, index) => {
          return (
            <Form.Item
              name={[index, "hasDefaultIntro"]}
              valuePropName="checked"
            >
              <Checkbox />
            </Form.Item>
          );
        },
      },
    ],
  };

  const _handler = {
    onClose: () => {
      props.onClose?.();
    },
    save: async () => {
      const values: { rows: INovelChannelAuth[] } = form.getFieldsValue(true);
      console.log(values);
      await apiSaveNovelChannelAuth({
        auths: values.rows.map((item) => {
          return {
            id: item.id,
            novelId: item.novelId,
            channelId: item.channelId,
            channelTagId: item.channelTagId,
            channelTitle: item.channelTitle,
            authType: item.authType,
            authStatus: item.authStatus,
            authStartDate: item.authStartDateDayjs?.format("YYYY-MM-DD"),
            authExpireDate: item.authExpireDateDayjs?.format("YYYY-MM-DD"),
            hasDefaultIntro: item.hasDefaultIntro,
          };
        }),
      });
      message.success("保存成功");
      props.onOk?.();
    },
  };

  const _fetch = {
    channelTagsAll: async () => {
      const resp = await apiChannelTagsAll();
      setChannelTagTreeMap(resp);
    },
    novelChannelAuths: async (novelId: number) => {
      const [channelList, channelAuthList] = await Promise.all([
        apiChannelAll(),
        apiNovelChannelAuth(novelId),
      ]);
      // 所有渠道里面找到可以授权的渠道
      const authChannelList = channelList.filter((item) => {
        // 配置不存在，直接过滤掉
        if (!item.channelNovelConfig) {
          return false;
        }
        // kind 为空，或者 kind 相同
        if (item.channelNovelConfig.kind?.includes(props.novel?.kind || "")) {
          return true;
        }
        if (
          item.channelNovelConfig.lengthType?.includes(
            props.novel?.lengthType || "",
          )
        ) {
          return true;
        }
        if (
          item.channelNovelConfig.contentType?.includes(
            props.novel?.contentType || "",
          )
        ) {
          return true;
        }

        return false;
      });

      const channelAuthMap = channelAuthList.reduce(
        (prev, cur) => {
          prev[cur.channelId] = cur;
          return prev;
        },
        {} as Record<number, INovelChannelAuth>,
      );
      form.setFieldsValue({
        rows: authChannelList.map((item) => {
          return {
            novelId: props.novel?.id,
            channelId: item.id,
            channelTitle: props.novel?.title,
            authType: dictsMap.NOVEL_CHANNEL_AUTH_TYPE?.[0]?.code,
            ...channelAuthMap[item.id],
            authStartDateDayjs: channelAuthMap[item.id]?.authStartDate
              ? dayjs(channelAuthMap[item.id]?.authStartDate)
              : undefined,
            authExpireDateDayjs: channelAuthMap[item.id]?.authExpireDate
              ? dayjs(channelAuthMap[item.id]?.authExpireDate)
              : undefined,
            channelInfo: item,
          } as INovelChannelAuth;
        }),
      });
    },
  };

  useEffect(() => {
    if (!props.visible || !props.novel?.id) {
      return;
    }
    _fetch.novelChannelAuths(props.novel.id);
  }, [props.visible, props.novel]);

  useEffect(() => {
    _fetch.channelTagsAll();
  }, []);

  return (
    <Drawer
      title={
        <div className="flex items-center justify-between">
          <span>渠道授权</span>
          <div>
            <Button type="primary" onClick={() => _handler.save()}>
              保存
            </Button>
          </div>
        </div>
      }
      width={1200}
      onClose={_handler.onClose}
      open={props.visible}
    >
      <div className="flex flex-col gap-2">
        <div className="flex flex-col gap-2">
          <div className="flex gap-2">
            <span className="text-gray-400">标题:</span>
            <span className="font-bold">{props.novel?.title}</span>
          </div>{" "}
          <div className="flex gap-2">
            <span className="text-gray-400">作者:</span>
            <span className="font-bold">{props.novel?.penName}</span>
          </div>
        </div>
        <Form form={form} className="rp-[.ant-form-item]:!mb-0">
          <Form.List name={"rows"}>
            {(fields) => {
              return (
                <Table
                  size="small"
                  columns={_ui.tableColumns}
                  dataSource={fields as unknown as INovelChannelAuth[]}
                  scroll={{
                    y: tableHeight,
                    x: "max-content",
                  }}
                  // rowKey={(record) => `${record.novelId}-${record.channelId}`}
                  locale={{
                    emptyText: "暂无数据",
                  }}
                  pagination={false}
                />
              );
            }}
          </Form.List>
        </Form>
      </div>
    </Drawer>
  );
}
